package com.ruoyi.projectAch.utils;

import com.ruoyi.projectAch.domain.WebPages;
import com.ruoyi.projectAch.mapper.WebPagesMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Component
public class URLTitleFetcherUtils {

    @Value("${pythonVersion}")
    private String python;

    @Value("${pythonScriptFolder}")
    private String pythonScriptFolder;

    @Autowired
    WebPagesMapper webPagesMapper;


    public void clean() {
        String commond = python + " " + pythonScriptFolder + "clean.py ";
        System.out.println("执行脚本：" + commond);
        System.out.println("执行结果：" + CommandExecutorUtils.executeCommand(commond));
    }

    /**
     * 获取指定URL的标题。
     *
     * @param url 要获取标题的URL
     * @return URL的标题，如果无法获取则返回null
     */
    public void setTitle(String url, WebPages webPages) {
        String commond = python + " " + pythonScriptFolder + "getUrlTitle.py " + url;
        System.out.println("执行脚本：" + commond);
        webPages.setTitle(CommandExecutorUtils.executeCommand(commond));
        System.out.println("获取标题：" + webPages.getTitle());
        webPagesMapper.updateWebPages(webPages);
    }

    public void getImage(String url) {
        String commond = python + " " + pythonScriptFolder + "getImage.py " + url;
        System.out.println("执行脚本：" + commond);
        System.out.println("截屏结果：" + CommandExecutorUtils.executeCommand(commond));
    }

    public void copyUrlPage(String url, WebPages webPages) {
        String commond = python + " " + pythonScriptFolder + "copyUrlPage.py " + url;
        System.out.println("执行脚本：" + commond);
        System.out.println("拷贝结果：" + CommandExecutorUtils.executeCommand(commond));
    }

    public void packageFiles(WebPages webPages) {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String timestampSuffix = timestamp.substring(timestamp.length() - 5);
        String zipName = webPages.getTitle() + "_" + timestampSuffix;
        zipName = FilenameSanitizerUtils.sanitizeFilename(zipName);
        System.out.println("文件名：" + zipName);
        String commond = python + " " + pythonScriptFolder + "package.py " + zipName;
        System.out.println("执行脚本：" + commond);
        CommandExecutorUtils.executeCommand(commond);
        zipName = zipName + ".zip";
        webPages.setFilePath(zipName);
        webPages.setFileName(zipName);
        webPages.setStatus("succeed");
        webPagesMapper.updateWebPages(webPages);
        System.out.println("执行结果：" + zipName);
    }
}
